﻿namespace Sidvall.Web.IO.Data
{
    public class ResourceResultCollection : System.Collections.ObjectModel.KeyedCollection<string, ResourceResult>
    {
        #region Public Members

        #region GetResourceItem

        public Sidvall.Security.ResourceItem GetResourceItem(string resource, string action)
        {
            var resourceResult = FindItem(resource);
            if (resourceResult == null)
                return null;
            var resourceActionResult = resourceResult.ResourceActionResults.FindItem(action);
            return resourceActionResult?.ResourceItem;
        }

        #endregion
        #region GetOrCreate

        public ResourceResult GetOrCreate(string resource)
        {
            var item = FindItem(resource);
            if (item == null)
            {
                item = new ResourceResult()
                {
                    Resource = resource,
                    ResourceActionResults = new ResourceActionResultCollection(),
                };
                Add(item);
            }
            return item;
        }

        #endregion
        #region FindItem

        public ResourceResult FindItem(string resource)
        {
            if (string.IsNullOrWhiteSpace(resource))
                return null;
            if (Contains(resource))
                return this[resource];
            return null;
        }

        #endregion
        #region GetKeyForItem

        protected override string GetKeyForItem(ResourceResult item)
        {
            if (item == null)
                throw new System.ArgumentNullException(nameof(item));
            return item.Resource;
        }

        #endregion

        #endregion
    }
}
